(function($) {

	$.fn.tree = function(options){
		Panel = {};
		var opts = $.extend(true, $.fn.tree.defaults, options);
		
		if(opts.events) {
			if(typeof opts.events.load == 'function') {
				opts.callback.onload = opts.events.load;
//				delete opts.events.load;
			}

			if(typeof opts.events.create == 'function') {
				opts.callback.oncreate = opts.events.create;
//				delete opts.events.create;
			}

			if(typeof opts.events.rename == 'function') {
				opts.callback.onrename = opts.events.rename;
//				delete opts.events.rename;
			}

			if(typeof opts.events.remove == 'string'){
				opts.callback.ondelete = function(n){
					var url = opts.events.remove + n.id;
					if(!$.fn.tree.defaults.events.remove_globle && $(n).attr('d_url'))
						url = $(n).attr('d_url')+($(n).attr('d_url').indexOf('id=')>0?n.id:'');
						
					$.get(url);
					delete url;
				}
			} else if(typeof opts.events.remove == 'function') {
				opts.callback.ondelete = opts.events.remove;
//				delete opts.events.remove;
			}

			if(typeof opts.events.move == 'function') {
				opts.callback.onmove = opts.events.move;
//				delete opts.events.move;
			}			
		}
			Panel.jsTree = $.tree_create();
			Panel.jsTree.init($(this), $.extend(true, {}, opts));
			
			Panel.creating = 0;
			
			// Functions
			Panel.loadContent = function(id) {
				// TODO something extends
			}
			Panel.move = function(n,r,h) {
				//server TODO something in server side
//				$.get("service?type=move&id=" + n.id + "&ref_id=" + (r === -1 ? 0 : r.id) + "&move_type=" + h, function (data) {
//					if(!n.id) n.id = data;
//				});
			}
			Panel.create	= function () { Panel.jsTree.create(false, (Panel.jsTree.container.find("li").size() == 0 ? -1 : false) ); }
			Panel.rename	= function () { Panel.jsTree.rename(); }
			Panel.remove	= function () { Panel.jsTree.remove(); }
			Panel.copy		= function () { if(Panel.jsTree.selected) { Panel.jsTree.copy(); } }
			Panel.cut		= function () { if(Panel.jsTree.selected) { Panel.jsTree.cut(); } }
			Panel.paste		= function () { Panel.jsTree.paste(); }

			// Keyboard shortcuts
			$(document)
				.bind('keydown', {combi:'up',		disableInInput: true} , function() { Panel.jsTree.get_prev(); return false; })
				.bind('keydown', {combi:'down',		disableInInput: true} , function() { Panel.jsTree.get_next(); return false; })
				.bind('keydown', {combi:'left',		disableInInput: true} , function() { Panel.jsTree.get_left(); return false; })
				.bind('keydown', {combi:'right',	disableInInput: true} , function() { Panel.jsTree.get_right(); return false; })
				.bind('keydown', {combi:'return',	disableInInput: true} , function() { if(Panel.jsTree.hovered) Panel.jsTree.select_branch(Panel.jsTree.hovered); return false; })
				.bind('keydown', {combi:'f2',		disableInInput: true} , function() { if(Panel.jsTree.hovered) Panel.jsTree.rename(); return false; })
				.bind('keydown', {combi:'f3',		disableInInput: true} , function() { if(Panel.jsTree.hovered) Panel.jsTree.update(); return false; })
				.bind('keydown', {combi:'del',		disableInInput: true} , function() { if(Panel.jsTree.selected) Panel.jsTree.remove(); return false; })
				.bind('keydown', {combi:'insert',	disableInInput: true} , function() { if(Panel.jsTree.selected) Panel.jsTree.create(); return false; })
				.bind('keydown', {combi:'ctrl+c',	disableInInput: true} , function() { Panel.jsTree.copy(); return false; })
				.bind('keydown', {combi:'ctrl+x',	disableInInput: true} , function() { Panel.jsTree.cut(); return false; })
				.bind('keydown', {combi:'ctrl+v',	disableInInput: true} , function() { Panel.jsTree.paste(); return false; })

			// Interface hooks
			$("#tree-panel .menu")
				.find("a").not(".lang")
					.bind("click", function () {
						try { Panel[$(this).attr("rel")](); } catch(err) { }
						this.blur();
					})
					.end().end()
				.children(".cmenu")
					.hover( function () { $(this).addClass("hover"); }, function () { $(this).removeClass("hover") })

			$("#tree-panel .menu a.lang")
				.live("click", function (event) {
					Panel.jsTree.show_lang(($(this).attr("href").replace(/.*?#/ig, "") - 1));  
					$(this).clone().prependTo($(this).parent()); 
					$(this).remove(); 
					if(Panel.jsTree.selected) Panel.loadContent(Panel.jsTree.selected.attr("id"));
					event.preventDefault();
					event.stopPropagation();
					return false;
				});

			
	};
	
	$.fn.tree.defaults = {
			associate : false, //define the tree associate with edit panel or not
			data : { type : "json", async : true, url : false },
			ui : { theme_path	: "images/themes/" },
//			rules : { draggable : "all", multiple : "ctrl" },
			events : {
				load : false,  			//load content URL
				load_global : true, 	//target of load content URL is global or not
				create : false,
				create_global : true,
				update : false,
				update_global : true,
				remove : false,
				remove_global : true,
				move : false,
				move_global : true
			},
			callback : {
//				beforechange : function (n, t) { 
//					return true;
//				}, 
//				onchange : function (n) { 
//					if(n.id) Panel.loadContent(n.id);
//				},
				// THINK OF ROLLBACK!
				oncreate : function (n, r, h, t) {
					if($.fn.tree.defaults.associate){
						//TODO
					} else {
						Panel.creating = 1;
						Panel.move(n,r,h);
					}
				},
				onrename : function (n,l,t,r) {
					if(Panel.creating == 1) {
//						Panel.loadContent(n.id);
						Panel.creating = 0;
						
						if(typeof $.fn.tree.defaults.events.create == 'string'){
							$.post($.fn.tree.defaults.events.create, { data : $(n).children("a:visible").text(), lang : ($.inArray(t.current_lang, t.settings.languages) + 1), ref_id : $(Panel.jsTree.selected[0].parentNode.parentNode).attr('id') }, function (data) {
								if(!n.id) n.id = data;
							});
						}
					} else {
						if(typeof $.fn.tree.defaults.events.rename == 'string'){
							$.get($.fn.tree.defaults.events.update, { data : $(n).children("a:visible").text(), lang : ($.inArray(t.current_lang, t.settings.languages) + 1), id : n.id });
						}
					}
				},
				onmove : function (n, r, h) {
					Panel.move(n,r,h);
					if(typeof $.fn.tree.defaults.events.move == 'string'){
						$.get($.fn.tree.defaults.events.move + n.id + "&ref_id=" + (r === -1 ? 0 : r.id) + "&move_type=" + h, function (data) {
							if(!n.id) n.id = data;
						});
					}
				},
				beforedelete : function (n) {
					return confirm("Are you sure you want to delete?");
				},
//				ondelete : function (n) {
//				},
				onload : function (t) { 
					t.select_branch(t.container.find("li:eq(0)"));
				}
			}
		};
	
	$.fn.tree.send = function(handle, msg) {
		window.top.document.message(handle, msg, 'content');
	};

	$.fn.tree.accept = function(handle, msg, ref_note) {
		ref_note = ref_note? ref_note : Panel.jsTree.selected;
		if(msg.attributes.id != ref_note){
			ref_note = msg.attributes.id.toString();
			if(ref_note && ref_note.indexOf('#')<0)
				ref_note = '#'+ref_note;
		}
		switch(handle){
		case 'c':
			$.tree_reference("tree-body").add(msg);
			break;
		case 'u':
			$.tree_reference("tree-body").update(msg, ref_note);
			break;
		case 'd':
			$.tree_reference("tree-body").remove(ref_note);
			break;
		default:
			break;
		}
	};
})(jQuery);